package cn.hn.comm;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.List;

import cn.hn.net.Kit;

public class LocalFiles {

	/**
	 * 创建文本文件.
	 * 
	 * @throws IOException
	 * 
	 */
	public File creatTxtFile(String file) {
		File filename = new File(file);
		try {
			if (!filename.exists()) {
				filename.createNewFile();
				System.err.println(filename + "已创建！");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return filename;
	}

	/**
	 * 读取文本
	 * 
	 * @param file
	 * @param charset
	 * @return
	 */
	public String readTxtFile(String file, String charset) {
		try {
			FileInputStream fis = new FileInputStream(file);
			Kit kit = new Kit();
			byte[] txt = kit.getBytes(fis, 9999);
			String strTxt = new String(txt, charset);
			return strTxt;

		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return null;
	}

	/**
	 * 读取文本文件.
	 * 
	 */
	public String readTxtFile(String file) {

		BufferedReader bufread;
		String read;
		FileReader fileread;
		String readStr = "";
		File filename = creatTxtFile(file);
		try {
			fileread = new FileReader(filename);
			bufread = new BufferedReader(fileread);
			try {
				while ((read = bufread.readLine()) != null) {
					readStr = readStr + read + "\r\n";
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// System.out.println("文件内容是:" + "\r\n" + readStr);
		return readStr;
	}

	/**
	 * 写文件.
	 * 
	 */
	public void writeTxtFile(String file, String newStr) throws IOException {
		File filename = creatTxtFile(file);
		String readStr = "";
		// 先读取原有文件内容，然后进行写入操作
		String filein = newStr + "\r\n" + readStr + "\r\n";
		RandomAccessFile mm = null;
		try {
			mm = new RandomAccessFile(filename, "rw");
			mm.writeBytes(filein);
		} catch (IOException e1) {
			// TODO 自动生成 catch 块
			e1.printStackTrace();
		} finally {
			if (mm != null) {
				try {
					mm.close();
				} catch (IOException e2) {
					// TODO 自动生成 catch 块
					e2.printStackTrace();
				}
			}
		}
	}

	// 递归查找函数，参数为file对象
	public void getFileName(String filePath, List<String> fileNames) {
		File f = new File(filePath);
		// File 数组
		File[] files = f.listFiles();

		for (int i = 0; i < files.length; i++) {
			// 递归出子目录
			if (files[i].isDirectory()) {
				System.out.println("子目录是：" + files[i].getName());
				getFileName(files[i].getAbsolutePath(), fileNames);
				// 递归出子文件
			} else {
				System.out.println(files[i].getAbsolutePath());
				fileNames.add(files[i].getAbsolutePath());
			}

		}
	}

}
